/**
 * WeeShop 声明
 * ===========================================================
 * 网站： https://www.darlang.com
 * 标题： ECShop 小程序「weeshop 」- 基于 ECShop 为后台系统开发的非官方微信商城小程序
 * 链接： https://www.darlang.com/?p=709
 * 说明： 源码已开源并遵循 Apache 2.0 协议，你有权利进行任何修改，但请保留出处，请不要删除该注释。
 * ==========================================================
 * Copyright 2019 darlang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ===========================================================
 */

// detail.js
import { PNT, setNavBarTitle, showToast, shopUrl, getCurrentPageUrl, pushPagePath} from "../../../utils/utils";
import { GetPointsDetail, ChangeFavoriteStatus, GetCheckShop, checkExchange} from '../../../utils/apis';
import WxParse from "../../../libs/wxParse/wxParse.js";


Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0, 
    commentsPreview: {
      grade: 3,
      updated_at: '2019-10-10',
    },//
    goods: {
      photos:[
        { 
          id:1,
          large: 
  'https://donglongshangshi.oss-cn-beijing.aliyuncs.com/images/201703/goods_img/0_P_1490209720480.jpg',
        },
         {
           id:2,
          large:
            'https://donglongshangshi.oss-cn-beijing.aliyuncs.com/images/201703/goods_img/0_P_1490209720480.jpg',
        },
        
      ],
      exchange_score:200,
      price:300,
      name: '美的智能家用多功能双胆电压力锅高压锅饭煲正品WCS5025 5L小家电 5L双胆 智能预约 大面板',
      is_shipping:1,
      review_rate:80,
      sales_count:30,
      good_stock:20,
      shop:1,
      properties:'',
      comment: [
        {
          user_pic: 'https://donglongshangshi.com/mobile/public/img/user_default.png',
          user_name: '詹丹',
          updated_at: '2019-10-10',
          grade: 4,
          content: '哒哒哒哒哒哒过过过过或或',
        },

      ],
    },// 商品信息
    propertyPopState: false,// 规格弹窗
    scoreInfo: 0,

    curProperty: '',// 当前选中的规格
    curGoodsNum: 1,
    curGoodsPrice: '',
    curGoodsStock: 10,
    curScoreState:2000,
    curStockState: false,// 规格是否通过
    consignee: '',// 收货地址
  },

  /**
 * 页面跳转
 * @author darlang
 */
  pushPath(e) {
    console.log(e)
    const items = e.currentTarget.dataset;
    // wx.navigateTo({
    //   url: '/pages/member/comment/list/list?goodsId=' + items.id ,
    // })
    // return;
    const pathData = [
      { type: 'cart', path: '/pages/shopping/cart/cart' },
      { type: 'comments', path: '/pages/member/comment/list/list?goodsId=' + items.id }
    ];
    if (items.type === 'home') {
      wx.reLaunch({
        url: '/pages/index/index'
      });
      return false;
    }
    pushPagePath(e, pathData);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(opt) {
    setNavBarTitle(PNT.points.detail);
    this.loginModal = this.selectComponent("#login-modal");
    this.setData({
      id: parseInt(opt.id)
    });
    this.getScoreInfo();
    if(!this.loginModal.check()){
      return false;
    }
  },
  // 保证弹出和关闭
  showbz: function () {
    this.setData({
      isRuleTrue: true
    })
  },
  hidebz: function () {
    this.setData({
      isRuleTrue: false
    })
  },
  /**
   * 登录回调
   * @author darlang
   */
  loginCallback(cb) {
    if (cb.detail.type === 'success') {
      // this.getProductInfo();
      // this.getConsignees();
    }
  },

  /**
 * 收藏/取消收藏
 * @author darlang
 */
  switchCollect() {
    if (!this.loginModal.check()) {
      return false;
    }
    var info = wx.getStorageSync('userInfo')
    let isLiked = this.data.isLiked || false;
    ChangeFavoriteStatus(this.data.id, info.user_id).then(res => {
      if (isLiked) {
        isLiked = false;
      } else {
        isLiked = true;
      }
      this.setData({
        isLiked: isLiked
      });
    });
  },
  //用户点击tab时调用
  titleClick: function (e) {
    let currentPageIndex =
      this.setData({
        //拿到当前索引并动态改变
        currentIndex: e.currentTarget.dataset.idx
      })
  },
  /**
   * 获取积分
   * @author darlang
   */
  getScoreInfo() {
    var self = this;
    var data = {};
    data.id = this.data.id;
    GetPointsDetail(data).then(res=>{
      if(res.error_code == 10000){
        WxParse.wxParse("goodsDetail", "html", res.data.detail.goods_desc, self);
        this.setData({
          exchangeInfo:res.data.detail,
          comment:res.data.comment,
          attr_spec: res.data.attr_spec.pro[""],
        })
      }
    })
  },

  /**
   * 获取商品
   * @author darlang
   */
  getProductInfo() {
    let self = this;
    //wx.showLoading({title: '加载中...',mask: true});
    GetGoodsDetail(this.data.id).then(res => {
      let rp = res.product;
      let curStockState = false;
      let curGoodsNum = 1;
      if (rp.good_stock === 0) {
        showToast("商品已经兑完", "error", 1800);
        curStockState = false;
        curGoodsNum = 0;
      }
      if (res.error_code === 0) {
        // 默认当前价格-积分
        let curPrice = rp.exchange_score || 0;

        self.setData({
          goods: rp,
          curGoodsPrice: curPrice,
          curGoodsStock: rp.good_stock,
          curGoodsNum,
          curStockState
        });
        this.getScoreInfo(rp.exchange_score);

      }
      // 处理图片，判断图片是否带有前缀，没有加前缀，前缀为配置中的 shopUrl
      // 注意：图片地址不允许为相对地址
      let cont = res.product.goods_desc;
      const IUREG = /src=("|')([^("|')]*)("|')/gi;
      if (cont) {
        cont = cont.replace(IUREG,(item,cap,cap2,cap3) => {
          if (cap2.indexOf('http') === 0) {
            return item;
          }else{
            return `src=${cap}${shopUrl}/${cap2}${cap3}`;
          }
        });
        WxParse.wxParse("goodsDetail", "html", cont, self);
      }
    });
  },

  /**
   * 关闭/开启弹窗
   * @author darlang
   */
  switchPopstate() {
    this.setData({
      propertyPopState: !this.data.propertyPopState
    });
  },


  
  /**
   * 修改商品数量
   * @author darlang
   */
  changeGoodsNum(e) {
    let type = e.currentTarget.dataset.type;
    let curGoodsNum = this.data.curGoodsNum;
    let curGoodsStock = this.data.curGoodsStock;
    let curGoodsPrice = this.data.curGoodsPrice;
    let scoreInfo = this.data.scoreInfo;
    let curStockState = true;
    let curScoreState = true;
    if (type === 'add') {
      curGoodsNum ++;
      if (curGoodsNum > 99999 && curGoodsNum <= curGoodsStock) {
        showToast('该商品限购99999件');
        curGoodsNum = 99999;
      }else{
        if (curGoodsNum >= curGoodsStock) {
          showToast('不能大于库存数量');
          curGoodsNum = curGoodsStock;
        }
      }
    }
    if (type === 'cut') {
      curGoodsNum --;
      if (curGoodsNum < 1) {
        showToast('请至少选择一件商品');
        curGoodsNum = 1;
      }
    }
    if (curGoodsNum*curGoodsPrice > scoreInfo) {
      curStockState = false;
      curScoreState = false;
    }
    this.setData({
      curGoodsNum,
      curStockState,
      curScoreState
    });
  },


  /**
   * 页面跳转
   * @author darlang
   */
  // pushPath(e) {
  //   const items = e.currentTarget.dataset;
  //   if (items.type === 'home') {
  //     wx.reLaunch({
  //       url: '/pages/index/index'
  //     });
  //     return false;
  //   }
  // },



  /**
   * 加入购物车
   * @author darlang
   */
  buyGoods(e) {
    if(!this.loginModal.check()){
      return false;
    }
    //检测收货地址
    var data = {};
    var info = wx.getStorageSync('userInfo');
    data.user_id = info.user_id;
    GetCheckShop(data).then(res=>{
      if(res.error_code !== 10000){
        wx.showModal({
          title: "温馨提示",
          content: "由于您尚未添加地址，请先添加地址.",
          // showCancel: false,
          success: function (cif) {
            if (cif.confirm) {
              wx.navigateTo({
                url: "/pages/member/address/edit/edit?type=add"
              });
            }
          }
        });
        return;
      }
    })
    let g = this.data.exchangeInfo;
    checkExchange(data).then(res=>{
      if(res.error_code == 10000){
        if (res.data < g.exchange_integral){
          wx.showToast({
            title: '积分不足',
            icon:'none',
          })
          return;
        }
        let consignee = this.data.consignee;
        let preOrder =
        {
          goods_id: this.data.exchangeInfo.goods_id,
          num: this.data.curGoodsNum,
          total_amount: this.data.exchangeInfo.exchange_integral,
          type: 'points',
          user_id: info.user_id,
        };

        wx.navigateTo({
          url: '/pages/shopping/checkout/checkout?is_exchange=1&preOrder=' + JSON.stringify(preOrder)
        });
        return false;

      }
    })
    // consignee: 3
    // order_product: "[{"goods_id":69,"property":[241,243],"num":1,"total_amount":1}]"


  },

  /**
   * 获取默认收货人,无默认选择第一条
   * @author darlang
   */
  getConsignees() {
    let consignee = '';
    GetConsigneeList().then(res => {
      if (res.consignees && res.consignees.length > 0) {
        for (let i = 0; i < res.consignees.length; i++) {
          let item = res.consignees[i];
          if (item.is_default) {
            consignee = item.id;
            break;
          }else{
            if (i+1 === res.consignees.length) {
              consignee = res.consignees[0].id;
            }
          }
        }
      }
      this.setData({
        consignee: consignee
      });
    });
  },

  /**
 * 收藏/取消收藏
 * @author darlang
 */
  switchCollect() {
    if (!this.loginModal.check()) {
      return false;
    }
    var info = wx.getStorageSync('userInfo')
    let isLiked = this.data.isLiked || false;
    ChangeFavoriteStatus(this.data.id, info.user_id).then(res => {
      if (isLiked) {
        isLiked = false;
      } else {
        isLiked = true;
      }
      this.setData({
        isLiked: isLiked
      });
    });
  },

  /**
   * 背景滚动事件
   * @author darlang
   */
  preventTouchMove(e) {
    console.log(e);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    // 页面渲染完成
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // 页面显示
    // this.getProductInfo();
    // this.getConsignees();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    // 页面隐藏
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 页面关闭
  }
});